package kr.hkit.androidcomplete03.ch25;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;

public class SDCardTest extends Activity {
	EditText edit;
	String mSDPath;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_sdcard);
		
		edit = (EditText) findViewById(R.id.ch25_sdcard_edittext);
		String ext = Environment.getExternalStorageState();
		if(ext.equals(Environment.MEDIA_MOUNTED)){
			mSDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		}else{
			mSDPath = Environment.MEDIA_UNMOUNTED;
		}
	}
	
	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.ch25_sdcard_test:
			String rootdir = Environment.getRootDirectory().getAbsolutePath();
			String datadir = Environment.getDataDirectory().getAbsolutePath();
			String cachedir = Environment.getDownloadCacheDirectory().getAbsolutePath();
			edit.setText(String.format("ext = %s\nroot=%s\ndata=%s\ncache=%s", mSDPath, rootdir, datadir, cachedir));
			break;

		case R.id.ch25_sdcard_save:
			File dir = new File(mSDPath + "/dir");
			dir.mkdir();
			File file = new File(mSDPath + "/dir/file.txt");
			try {
				FileOutputStream fos = new FileOutputStream(file);
				String str = "This file exists in SDcard;";
				fos.write(str.getBytes());
				fos.close();
				edit.setText("write Success");
			} catch (FileNotFoundException e) {
				edit.setText("File Not Found" + e.getMessage());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				edit.setText(e.getMessage());
			} catch(SecurityException e){
				edit.setText("Security Exception");
			}
			break;
			
		case R.id.ch25_sdcard_load:
			try {
				FileInputStream fis = new FileInputStream(mSDPath + "/dir/file.txt");
				byte[] data = new byte[fis.available()];
				fis.close();
				
				edit.setText(new String(data));
			} catch (FileNotFoundException e) {
				edit.setText("File Not Found");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}
